package com.mushuilingfeng.ddd.user.domain.org.event;

import cn.hutool.core.util.StrUtil;
import com.mushuilingfeng.ddd.user.domain.org.entity.Org;
import com.mushuilingfeng.ddd.user.domain.org.entity.OrgApply;
import com.mushuilingfeng.ddd.user.domain.org.enums.OrgApplyStatusEnum;
import com.mushuilingfeng.ddd.user.domain.org.repository.IOrgApplyRepository;
import com.mushuilingfeng.ddd.user.domain.org.repository.IOrgRepository;
import com.mushuilingfeng.ddd.framework.AsDomainEventSubscribe;
import com.mushuilingfeng.ddd.framework.event.IDomainEventListener;
import com.mushuilingfeng.ddd.framework.factory.DomainRepositoryFactory;
import lombok.extern.slf4j.Slf4j;


/**
 * 领域事件，可以在领域内进行消费，也可以在领域外进行消费。
 * 此处示例，就是在领域内进行消费
 *
 * @author
 * @date 2024/9/24
 */
@AsDomainEventSubscribe(eventCls = OrgApplyCheckEvent.class)
@Slf4j
public class OrgApplyCheckEventSubscribe implements IDomainEventListener<OrgApplyCheckEvent> {

    @Override
    public void onEvent(OrgApplyCheckEvent event) {
        log.info("收到机构注册申请单被审核事件，申请单ID = {}", event.getOrgApplyId());
        // 发送邮件通知申请人
        OrgApply orgApply = DomainRepositoryFactory.getRepository(IOrgApplyRepository.class).get(event.getOrgApplyId());
        sendEmail(orgApply);
        if (orgApply.getStatus() == OrgApplyStatusEnum.CHECK_PASS.getCode()) {
            log.info("开始生成新的机构！！申请单ID = {}", event.getOrgApplyId());
            Org applyOrg = orgApply.getOrgApplyRequest().getApplyOrg();
            if (StrUtil.isBlankIfStr(applyOrg.getParentOrgCode())) {
                applyOrg.saveNew();
            } else {
                DomainRepositoryFactory.getRepository(IOrgRepository.class).getByOrgCode(applyOrg.getParentOrgCode()).addChildOrg(applyOrg);
            }
            // 重新更新申请单
            orgApply.associateResultOrg(applyOrg);
        }
    }

    private void sendEmail(OrgApply orgApply) {
        String msg = "您的机构注册申请单已被审核，请查看审核结果。";
        log.info("发送邮件通知申请人，内容 = {}", msg);
        log.info("发送邮件给给用户：邮箱={}，用户={}", orgApply.getOrgApplyRequest().getApplyUserEmail(), orgApply.getOrgApplyRequest().getApplyUserName());
    }

}
